#pragma once

#include "oj_model_mysql.hpp"
// #include "oj_model.hpp"
#include "oj_view.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"

#include <mutex>
#include <vector>
#include <string>
#include <cassert>
#include <fstream>

#include <jsoncpp/json/json.h>

namespace ns_control
{
    using namespace ns_model;
    using namespace ns_view;
    using namespace ns_log;
    using namespace ns_util;
    using namespace httplib;

    const string &ServiceMachineConf = "./conf/service_machine.conf";
    struct Machine
    {
        string ip;       // 编译服务的ip
        int port;        // 端口
        uint64_t load;   // 负载数
        std::mutex *mtx; // 锁

        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}

        // 提升负载
        void IncLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        // 减少负载
        void DecLoad()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }
        void ResetLoad()
        {
            if (mtx)
                mtx->lock();
            load=0;
            if (mtx)
                mtx->unlock();
        }
        // 获得负载个数
        uint64_t GetLoad()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();
            return _load;
        }
    };
    class LoadBalance
    {
    private:
        vector<Machine> machines;
        // 用下标来表示对应的主机
        vector<int> online;
        vector<int> offline;

        std::mutex mtx;

    public:
        LoadBalance()
        {
            assert(Load(ServiceMachineConf));
            LOG(INFO) << "加载配置文件成功" << std::endl;
        }
        ~LoadBalance() {}

    public:
        bool Load(const string &ServiceMachineConf)
        {
            std::ifstream in(ServiceMachineConf);
            if (!in.is_open())
            {
                LOG(FALSE) << "加载编译服务器失败" << std::endl;
                return false;
            }
            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tokens;
                FileSplit::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(FALSE) << "编译主机配置文件出错" << std::endl;
                    continue;
                }
                Machine machine;

                machine.ip = tokens[0];
                machine.port = std::atoi(tokens[1].c_str());
                machine.load = 0;
                machine.mtx = new std::mutex;

                online.push_back(machines.size());
                machines.push_back(machine);
            }
            in.close();
            return true;
        }
        bool SmartChoise(int *id, Machine **m)
        {
            mtx.lock();

            int online_sum = online.size();
            if (online_sum == 0)
            {
                mtx.unlock();
                LOG(FALSE) << "所以编译服务都下线了" << std::endl;
                return false;
            }
            uint64_t min_load = machines[online[0]].GetLoad();
            *id = online[0];
            *m = &machines[online[0]];
            for (int i = 0; i < online_sum; i++)
            {
                uint64_t cur_load = machines[online[i]].GetLoad();
                if (min_load > cur_load)
                {
                    min_load = cur_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }
            mtx.unlock();
            return true;
        }
        void OffLineMachine(int id)
        {
            mtx.lock();
            for (auto x = online.begin(); x != online.end(); x++)
            {
                if (*x == id)
                {
                    machines[id].ResetLoad();
                    online.erase(x);
                    offline.push_back(id);
                    break;
                }
            }
            mtx.unlock();
        }
        void InLineMachine()
        {
            mtx.lock();
            online.insert(online.begin(),offline.begin(),offline.end());
            offline.clear();
            mtx.unlock();
            LOG(INFO)<<"所有主机都上线了"<<std::endl;
        }
    };

    class Control
    {
    private:
        Model _model;
        View _view;
        LoadBalance _loadBalance;

    public:
        Control() {}
        ~Control() {}

    public:
        bool AllQuestions(string *html)
        {
            vector<Question> all;
            if (_model.GetAllQuestions(&all))
            {
                // 把所以的题目进行渲染
                _view.AllExpand(all, html);

                return true;
            }
            else
            {
                *html = "渲染全部题目失败";
                LOG(ERROR) << "渲染全部题目失败" << endl;
                // 失败
                return false;
            }
        }
        bool OneQuestion(const string &number, string *html)
        {
            Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                // 成功，渲染
                _view.OneExpand(q, html);

                return true;
            }
            else
            {
                *html = "渲染一个题目失败";
                LOG(ERROR) << "渲染一个题目失败" << endl;
                // 失败
                return false;
            }
        }
        void BackOnline()
        {
            _loadBalance.InLineMachine();
        }
        void Judge(const string &number, const string &in_json, string *out_json)
        {
            Question q;
            _model.GetOneQuestion(number, &q);
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            string code = in_value["code"].asString();

            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + q.tail;
            compile_value["cpu"] = q.cpu_limit;
            compile_value["mem"] = q.mem_limit;

            Json::StyledWriter writer;
            string compile_string = writer.write(compile_value);

            // 选择主机
            while (true)
            {
                int id = 0;
                Machine *m;
                if (!_loadBalance.SmartChoise(&id, &m))
                {
                    break;
                }
                LOG(INFO) << "选择主机成功：id" << id << "主机详情" << m->ip << ":" << m->port << "负载" << m->load << endl;

                m->IncLoad();
                Client cli(m->ip, m->port);
                if (auto ret = cli.Post("/compile_run", compile_string, "application/json;charset=utf-8"))
                {
                    if (ret->status == 200)
                    {
                        *out_json = ret->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译运行成功" << endl;
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    LOG(INFO) << "主机下线：id" << id << "主机详情" << m->ip << ":" << m->port << endl;
                    _loadBalance.OffLineMachine(id);
                }
            }
        }
    };
}